from flask import request
import logging

# 获取logger
logger = logging.getLogger(__name__)

def get_client_ip():
    """
    获取客户端真实IP地址
    优先从X-Forwarded-For等代理头中获取，如果不存在则使用request.remote_addr
    
    返回:
    - 字符串形式的IP地址
    """
    # 记录所有请求头，帮助调试
    headers_log = {key: value for key, value in request.headers.items() 
                   if key.lower() in ['x-forwarded-for', 'x-real-ip', 'http_x_forwarded_for', 
                                     'http_x_real_ip', 'x-original-forwarded-for', 'remote-addr']}
    logger.info(f"[IP检测] 请求头: {headers_log}, remote_addr: {request.remote_addr}")
    
    # 检查各种代理头
    if request.headers.get('X-Forwarded-For'):
        # X-Forwarded-For格式为: client, proxy1, proxy2, ...
        # 取列表中第一个IP作为真实客户端IP
        ip = request.headers.get('X-Forwarded-For').split(',')[0].strip()
        logger.info(f"[IP检测] 使用X-Forwarded-For: {ip}")
        return ip
    elif request.headers.get('X-Real-IP'):
        ip = request.headers.get('X-Real-IP')
        logger.info(f"[IP检测] 使用X-Real-IP: {ip}")
        return ip
    elif request.headers.get('HTTP_X_FORWARDED_FOR'):
        ip = request.headers.get('HTTP_X_FORWARDED_FOR').split(',')[0].strip()
        logger.info(f"[IP检测] 使用HTTP_X_FORWARDED_FOR: {ip}")
        return ip
    elif request.headers.get('HTTP_X_REAL_IP'):
        ip = request.headers.get('HTTP_X_REAL_IP')
        logger.info(f"[IP检测] 使用HTTP_X_REAL_IP: {ip}")
        return ip
    elif request.headers.get('X-Original-Forwarded-For'):
        ip = request.headers.get('X-Original-Forwarded-For').split(',')[0].strip()
        logger.info(f"[IP检测] 使用X-Original-Forwarded-For: {ip}")
        return ip
    
    # 如果没有代理头信息，使用remote_addr
    logger.info(f"[IP检测] 使用remote_addr: {request.remote_addr}")
    return request.remote_addr 